package com.bookstore.services.Impl;

import com.bookstore.mappers.BookMapper;
import com.bookstore.pojo.Book;
import com.bookstore.pojo.Page;
import com.bookstore.services.BookService;
import com.bookstore.utils.SqlSessionUtil;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * 图书业务逻辑实现
 */
public class BookServiceImpl implements BookService {

    SqlSession sqlSession=SqlSessionUtil.getSqlSession();
    BookMapper mapper = sqlSession.getMapper(BookMapper.class);
    @Override
    public boolean add(Book book) {
        return mapper.insert(book)>0;
    }

    @Override
    public boolean update(Book book) {
        return mapper.updateByPrimaryKey(book)>0;
    }

    @Override
    public boolean delete(Book book) {
        return  mapper.deleteByPrimaryKey(book.getId())>0;
    }

    @Override
    public Book getOne(Book book) {
        return mapper.selectByPrimaryKey(book.getId());
    }


    @Override
    public Page<Book> getPage(String pageNo, String pageSize) {
//        将用户传入数据封装
        Page<Book> page = new Page<>();
        int pn =1;
        int ps= page.getPageSize();
        try {
            pn = Integer.parseInt(pageNo);
            pn=pn>0?pn:1;
        } catch (Exception e) {
            e.getMessage();
        }
        try {
            ps = Integer.parseInt(pageSize);
        } catch (Exception e) {
            e.getLocalizedMessage();
        }
        return page;
    }

    @Override
    public List<Book> getPageByPrice(String min, String max, String pageNo, String pageSize) {
        double minPrice = 1;
        double maxPrice = Double.MAX_VALUE;
        int curNum=1;
        int size=Integer.MAX_VALUE;
        try {
            min=min==""?"0":min;
            minPrice = Double.parseDouble(min);

        } catch (Exception e) {
            e.getLocalizedMessage();
        }
        try {
            max=max==""?"10000000":max;
            maxPrice = Double.parseDouble(max);
        } catch (Exception e) {
            e.getLocalizedMessage();
        }
        try {
            pageNo=pageNo==""?"1":pageNo;
            curNum=Integer.parseInt(pageNo);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        try {
            pageSize=pageSize==""?"10":pageNo;
            size=Integer.parseInt(pageSize);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        PageHelper.startPage(curNum,size);
        List<Book> list = mapper.getPageList(minPrice, maxPrice);
        return list;
    }


}
